package com.soushangxing.comfyuibackendv2.service

import com.soushangxing.comfyuibackendv2.entity.FileEntity
import com.soushangxing.comfyuibackendv2.repository.AliyunRepository
import com.soushangxing.comfyuibackendv2.repository.FileRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.util.*

@Service
class FileService {

    @Autowired
    lateinit var aliyunRepository:AliyunRepository
    @Autowired
    lateinit var fileRepository:FileRepository

    @Value("\${aliyun.oss.domain}")
    private lateinit var endpoint: String

    /**
     * 上传
     */
    fun putFile(objectName: String, data: ByteArray){
        aliyunRepository.putObject(objectName, data)
    }

    /**
     * 删除
     */
    fun deleteFile(objectName: String){
        aliyunRepository.deleteObject(objectName)
    }

    /**
     * 上传文件，并返回文件实体对象
     */
    fun saveFile(file:MultipartFile, type:String = "input") : FileEntity?{
        try {
            val originalFilename = file.originalFilename!!
            val fileExtension = originalFilename.substringAfterLast('.')
            val fileRandomString = UUID.randomUUID().toString()
            val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
            val currentDate = dateFormat.format(Date())
            var path = "ComfyUI/${type}/${currentDate}/${fileRandomString}" +"."+ fileExtension
            putFile(path, file.bytes)
            var completePath = endpoint + "/" + path

            val fileEntity = FileEntity()
            fileEntity.path = completePath
            fileEntity.relativePath = path
            fileEntity.previewPath = path + "?x-oss-process=image/resize,m_fill,w_{width},h_{height}"
            fileEntity.createTime = LocalDateTime.now()
            fileEntity.type = type
            fileRepository.save(fileEntity)
            return fileEntity
        } catch (e:Exception) {
            println(e.stackTrace)
            println(e.message)
            return null
        }

    }

    /**
     * 上传文件，并返回文件实体对象
     *  （通过ByteArray传的）
     */
    fun saveFile(file:ByteArray, type:String = "output") : FileEntity?{
        try {
            val fileExtension = "png"
            val fileRandomString = UUID.randomUUID().toString()
            var path = "ComfyUI/${type}/${fileRandomString}" +"."+ fileExtension
            putFile(path, file)
            var completePath = endpoint + "/" + path

            val fileEntity = FileEntity()
            fileEntity.path = completePath
            fileEntity.relativePath = path
            fileEntity.previewPath = path + "?x-oss-process=image/resize,m_fill,w_{width},h_{height}"
            fileEntity.createTime = LocalDateTime.now()
            fileEntity.type = type
            fileRepository.save(fileEntity)
            return fileEntity
        } catch (e:Exception) {
            println(e.stackTrace)
            println(e.message)
            return null
        }
    }

    /**
     * 移除文件（数据库与实体类）
     * fileName也即relativePath
     */
    fun removeFile(fileName: String) {
        return try {
            // 从数据库中查找 FileEntity 对象
            val fileEntity = fileRepository.findByRelativePath(fileName)

            if (fileEntity != null) {
                // 删除数据库中的 FileEntity 记录
                fileRepository.delete(fileEntity)

                // 删除阿里云上的文件
                deleteFile(fileEntity.relativePath)
            } else {
                println("FileEntity 不存在，无法删除文件")
            }
        } catch (e: Exception) {
            println(e.message)
        }
    }

}
